<template>
  <div class="wrapper">
    <xdh-curd ref="list" v-bind="curdProps" :listTitle="listTitle" :query="queryData">
      <template slot="filter-items">
        <el-form-item prop="keyword">
          <el-input placeholder="请输入关键字进行查询" v-model="queryData.keyword"></el-input>
        </el-form-item>
      </template>
      <template slot="table-columns" slot-scope="scope">
        <!--<el-table-column type="selection"></el-table-column>-->
        <el-table-column type="index"></el-table-column>
        <el-table-column v-for="cols in tableColumns"
                         :key="cols.valuezd"
                         v-if="checkRow.includes(cols.valuezd)"
                         :prop="cols.valuezd"
                         :label="cols.zdmc"
                         :sortable="Boolean(!cols.sfpx)"
                         v-bind="Boolean(!cols.sfss) ? {renderHeader:renderFilterHeader}:{}"
                         min-width="100"></el-table-column>
        <!--v-bind="Boolean(!cols.sfss) ? {filterMethod:filterSingleProp,filters:getFilterCols(cols.valuezd),filterMultiple:false} :{}"-->

      </template>

      <template slot="table-tool" slot-scope="prop">
        <el-button size="mini" @click="handleFormList(prop.row)" plain v-if="tabProps.type==='usertask1'">新增</el-button>
        <el-button size="mini" class="row-filter-btn" plain>筛选列</el-button>
        <div class="row-filter" v-show="showRowFilter">
          <el-checkbox-group v-model="checkRow"
                             :min="1">
            <div v-for="cols in tableColumns" :key="cols.valuezd">
              <el-checkbox :label="cols.valuezd">{{cols.zdmc}}</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </template>

      <template slot="table-handle-column" slot-scope="prop">
        <el-tooltip content="流程图" placement="top">
          <el-button size="mini" @click="handleViewFlow(prop.row)">
            <i class="iconfont icon-relation" style="line-height:0.5;"></i>
          </el-button>
        </el-tooltip>
        <el-tooltip content="重新申请" placement="top" v-if="prop.row.button === '0'">
          <el-button size="mini" @click="handleReapply(prop.row)">
            <i class="iconfont icon-reset" style="line-height:0.5;"></i>
          </el-button>
        </el-tooltip>
        <el-tooltip content="审批" placement="top" v-if="prop.row.button === '1'">
          <el-button icon="el-icon-check" size="mini" @click="handleApproval(prop.row)">
          </el-button>
        </el-tooltip>
        <el-tooltip content="反馈" placement="top" v-if="prop.row.button === '5'">
          <el-button size="mini" @click="handleFeedback(prop.row)">
            <i class="iconfont icon-redo" style="line-height:0.5;"></i>
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top" v-if="prop.row.button === '2'">
          <el-button icon="el-icon-delete" size="mini" @click="handleRemove(prop.row)">
          </el-button>
        </el-tooltip>
        <el-tooltip content="查看详情" placement="top" v-if="prop.row.button === '3'||'4'">
          <el-button icon="el-icon-view" size="mini" @click="handleView(prop.row)">
          </el-button>
        </el-tooltip>
      </template>
    </xdh-curd>

    <xdh-dialog title="表单选择"
                :closed="formDialogVisible">
      <el-form>
        <el-form-item>
          <el-select v-model="clueForm.formId" style="width:100%;">
            <el-option v-for="item in formList" :key="item.pkValue" :label="item.name"
                       :value="item.pkValue"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="formDialogCancel">取 消</el-button>
        <el-button type="primary" @click="formDialogSave">确 定</el-button>
      </div>
    </xdh-dialog>

    <clue-dialog ref="clueDialog"
                 :form-id="clueForm.formId"
                 :task-id="clueForm.taskId"
                 :is-view-num="clueForm.isViewNum"
                 :clue-row="clueRow"
                 :is-audit="isAudit"
                 :clue-state="clueState"
                 :title="clueDialogTitle"
                 @on-submit="handleSubmit"></clue-dialog>

    <xdh-dialog title="流程图"
                :closed.sync="flowDialogVisible"
                width="90%"
                height="450px">
      <div v-loading="loading"
           style="height:330px;width: 100%;overflow:auto;padding-top:50px;white-space:nowrap;"
           element-loading-background="rgba(0, 0, 0, 0.75)">
        <div class="process-box" v-for="(list,index) in processList" ref="process">
          <div class="process-circle">
            <span class="process-name">{{list.label}}</span>
            <i :class="'iconfont '+list.icon"></i>
          </div>
          <div class="process-line" v-show="index+1 !== processList.length">
            <div class="process-line_to"><i class="el-icon-arrow-right"></i></div>
          </div>
        </div>
        <div class="returnLine-box" v-show="returnShow">
          <div class="returnLine-left" :style="leftStyle"></div>
          <div class="returnLine-right" :style="rightStyle"></div>
          <div class="process-line returnLine-line-left" :style="leftLineStyle">
            <div class="process-line_to"><i class="el-icon-arrow-left"></i></div>
          </div>
          <div class="process-circle returnLine-circle" :style="circleStyle">
            <span class="process-name">退回</span>
            <i class="iconfont icon-reset"></i>
          </div>
          <div class="process-line returnLine-line-right" :style="rightLineStyle">
            <div class="process-line_to"><i class="el-icon-arrow-left"></i></div>
          </div>
        </div>
      </div>
    </xdh-dialog>

    <xdh-dialog title="删除原因"
                :closed="removeDialogVisible">
      <el-form :model="currentModel">
        <el-form-item>
          <el-input type="textarea" v-model="deleteReason"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="removeDialogCancel">取 消</el-button>
        <el-button type="primary"
                   @click="removeDialogSave">确 定
        </el-button>
      </div>
    </xdh-dialog>

    <div class="filter-box" v-show="isShowFilterBox" :style="filterBoxStyle">
      <div v-for="(item,index) in rowFilterData" :key="index" @click="showFilterResult(item.label)">{{item.label}}</div>
    </div>
  </div>
</template>
<style type="text/scss" lang="scss" scoped>
  .wrapper {
    height: 100%;
  }

  .process-box {
    display: inline-block;
  }

  .process-circle {
    float: left;
    width: 110px;
    height: 110px;
    border-radius: 50%;
    background: rgba(90, 123, 167, 1);
    text-align: center;
    position: relative;
    .process-name {
      position: absolute;
      top: -30px;
      left: 50%;
      transform: translateX(-50%);
      line-height: 30px;
      font-size: 20px;
      font-weight: bold;
    }
    .iconfont {
      line-height: 1.4;
      color: #fff;
      font-size: 80px;
      font-weight: bold;
    }
  }

  .process-circle-pass {
    background: rgba(228, 159, 56, 1);
  }

  .process-line {
    float: right;
    margin-top: 47.5px;
    width: 230px;
    height: 15px;
    background: rgba(90, 123, 167, 1);
    position: relative;
    &_to {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 25px;
      height: 25px;
      border-radius: 50%;
      box-shadow: 0 0 0 5px rgba(90, 123, 167, 1);
      i {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        color: rgba(90, 123, 167, 1);
        font-size: 22px;
        font-weight: 800;
      }
    }
  }

  .process-line-pass {
    background: rgba(228, 159, 56, 1);
    .process-line_to {
      box-shadow: 0 0 0 5px rgba(228, 159, 56, 1);
      i {
        color: rgba(228, 159, 56, 1);
      }
    }
  }

  .returnLine-box {
    position: relative;
    .returnLine-left, .returnLine-right {
      position: absolute;
      height: 100px;
      width: 15px;
      top: -6px;
      background: rgba(237, 102, 64, 1);
    }
    .returnLine-circle {
      background: rgba(237, 102, 64, 1);
      position: absolute;
      top: 30px;
      left: 0px;
    }
    .returnLine-line-left {
      background: rgba(237, 102, 64, 1);
      position: absolute;
      left: 60px;
      top: 31.5px;
      .process-line_to {
        box-shadow: 0 0 0 5px rgba(237, 102, 64, 1);
        i {
          color: #fff;
        }
      }
    }
    .returnLine-line-right {
      background: rgba(237, 102, 64, 1);
      position: absolute;
      left: 355px;
      top: 31.5px;
      .process-line_to {
        box-shadow: 0 0 0 5px rgba(237, 102, 64, 1);
        i {
          color: #fff;
        }
      }
    }
  }

  .row-filter, .el-table-filter {
    z-index: 5;
    position: absolute;
    top: 40px;
    right: 0;
    height: 240px;
    overflow-y: auto;
    border: 1px solid #00f;
    background: #144587;
    padding: 10px 15px;

    .el-checkbox {
      color: #333;
    }

  }

  .filter-box {
    width: 150px;
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
    position: absolute;
    border: 1px solid #00f;
    background: #144587;
    color: #fff;
    font-size: 12px;
    div {
      line-height: 30px;
      height: 30px;
      padding: 0 10px;
      overflow: hidden;
      cursor: pointer;
      :hover {
        background: #1685d7;
      }
    }
  }

  .filter-row-btn {
    opacity: 0.7
  }

</style>

<script>
  import Vue from 'vue'
  import XdhCurd from '../widgets/xdh-curd'
  import XdhDialog from '../widgets/xdh-dialog'
  import clueList from '../base/mixin/clue-clue-list'
  import formList from '../base/mixin/form-form-list'
  import sysDictionary from '../base/mixin/sys-dictionary'
  import ClueDialog from '../components/clue/clue-dialog.vue'
  import {on, off} from 'element-ui/lib/utils/dom'

  export default {
    components: {
      XdhDialog,
      ClueDialog,
      XdhCurd
    },
    props: {
      query: {
        type: Object
      },
      listTitle: {
        type: String
      },
      curdProps: {
        type: Object
      },
      tabProps: {
        type: Object
      }
    },
    mixins: [clueList, formList, sysDictionary],
    data() {
      return {
        filterBoxStyle: {},
        isShowFilterBox: false,
        rowFilterData: [],
        filterHeader: {},
        showRowFilter: false,
        checkRow: [],
        queryData: Object.assign({}, this.query),
        keyword: null,
        processList: [
          {
            result: '1',
            backNode: true,
            audittime: '',
            name: 'usertask1',
            bz: '',
            auditor: '',
            label: '线索上报',
            sendBack: false
          }, {
            result: '1',
            backNode: false,
            audittime: '2018-07-11 10:19:48',
            name: 'usertask11',
            bz: '123123123',
            auditor: '1111',
            label: '市单位审批',
            sendBack: true
          }, {
            result: '0',
            backNode: false,
            audittime: '2018-07-11 10:20:31',
            name: 'usertask111',
            bz: '测试流程',
            auditor: '1111',
            label: '省单位审批',
            sendBack: true
          }, {
            result: '',
            backNode: false,
            audittime: '',
            name: 'usertask1111',
            bz: '',
            auditor: '',
            label: '分配下发',
            sendBack: true
          }
        ],
        returnShow: false,
        loading: false,
        leftStyleNum: '',
        rightStyleNum: '',
        circleStyleNum: '',
        leftLineStyleWidth: '',
        rightLineStyleLeft: '',
        vm: null,
        formList: [],
        tableColumns: [],
        clueForm: {
          formId: '20180704100937150779',
          isViewNum: 0,
          processdefinitionid: '',
          taskId: ''
        },
        clueRow: {},
        clueState: null,
        clueDialogTitle: null,
        currentModel: {},
        formDialogVisible: true,
        removeDialogVisible: true,
        flowDialogVisible: true,
        isAudit: false,
        deleteReason: null,
        filterCols: {}
      }
    },
    created() {
      if (this.curdProps.mixin) {
        this.vm = new Vue(this.curdProps.mixin)
      }
      this.getTableCols()
      this.bindEvents()
    },
    mounted() {
    },
    computed: {
      leftStyle() {
        return {
          left: this.leftStyleNum
        }
      },
      rightStyle() {
        return {
          left: this.rightStyleNum
        }
      },
      circleStyle() {
        return {
          left: this.circleStyleNum
        }
      },
      leftLineStyle() {
        return {
          width: this.leftLineStyleWidth
        }
      },
      rightLineStyle() {
        return {
          width: this.leftLineStyleWidth,
          left: this.rightLineStyleLeft
        }
      }
    },
    methods: {
      showFilterBox(type) {
        const handler = function () {
          const documentBody = window.document.body
          const e = window.event
          const pos = {
            left: e.clientX + documentBody.scrollLeft - documentBody.clientLeft - 150 + 'px',
            top: e.clientY + documentBody.scrollTop - documentBody.clientTop + 20 + 'px'
          }
          this.rowFilterData = [...this.filterCols[type + 'Filter']]
          this.filterBoxStyle = pos
        }
        return handler.bind(this)
      },
      renderFilterHeader(h, obj) {
        return h('div',
          [
            obj.column.label,
            h('span', {
              'class': 'iconfont icon-sort-down filter-row-btn',
              on: {click: this.showFilterBox(obj.column.property)}
            })
          ])
      },
      showFilterResult(value) {
        this.queryData.keyword = value;
        this.$nextTick(() => {
          this.reloadList()
          this.isShowFilterBox = false
        })
      },
      getFilterCols(type) {
        return this.filterCols[type + 'Filter']
      },
      renderFilterData(isFlag, type) {
        if (!isFlag) {
          this.$set(this.filterCols, type + 'Filter', [])
          this.getDictList({dictValue: type}).then(res => {
            this.filterCols[type + 'Filter'] = res
          })
        }
      },
      bindEvents() {
        on(window, 'click', this.showFilterRow)
      },
      showFilterRow(e) {
        e.stopPropagation()
        if (document.getElementsByClassName('row-filter-btn')[0].contains(e.target)) {
          this.showRowFilter = !this.showRowFilter
        } else if (!document.getElementsByClassName('row-filter')[0].contains(e.target)) {
          this.showRowFilter = false
        }

        if (document.getElementsByClassName('filter-row-btn')[0].contains(e.target)) {
          this.isShowFilterBox = !this.isShowFilterBox
        } else if (!document.getElementsByClassName('filter-box')[0].contains(e.target)) {
          this.isShowFilterBox = false
        }
      },
      reloadList() {
        this.$refs.list.reload()
      },
      getTableCols() {
        // 写死 ltId:1
        this.vm['getClueCols']({ltId: 1}).then(res => {
          this.tableColumns = res
          this.checkRow = res.map(n => n.valuezd)
          res.forEach(item => {
            this.renderFilterData(item.sfss, item.valuezd)
          })
        })

        // 获取表单列表
        this.fetchFormFormList({limit: 1000, page: 1}).then(res => {
          this.formList = res.list
        })
      },
      /**
       * 打开自定义表单弹窗
       */
      openDialog() {
        this.clueState = null
        this.clueForm.isViewNum = 0
        this.isAudit = false
        this.$refs.clueDialog.cancelDialog()
      },
      /**
       * 新增线索
       * @param row
       */
      handleAddClue(row) {
        this.openDialog()
        this.clueDialogTitle = '新增线索'
        this.clueRow = {}
        this.clueForm.taskId = null
      },
      /**
       * 重新申请
       * @param row
       */
      handleReapply(row) {
        this.openDialog()
        this.clueDialogTitle = '重新申请'
        this.clueForm.taskId = row.processinstanceid
        this.clueForm.formId = row.formId
      },
      /**
       * 审批线索
       * @param row
       */
      handleApproval(row) {
        this.openDialog()
        this.clueDialogTitle = '线索审批'
        this.clueForm.taskId = row.processinstanceid
        this.clueRow = row
        this.isAudit = true
        this.clueForm.isViewNum = 1
        this.clueForm.formId = row.formId
      },
      /**
       * 线索反馈
       * @param row
       */
      handleFeedback(row) {
        this.openDialog()
        this.clueDialogTitle = '线索反馈'
        this.clueForm.taskId = row.processinstanceid
        this.clueRow = row
        this.isAudit = true
        this.clueState = 'feedback'
        this.clueForm.isViewNum = 1
        this.clueForm.formId = row.formId
      },
      /**
       * 查看线索详情
       * @param row
       */
      handleView(row) {
        this.openDialog()
        this.clueDialogTitle = '线索详情'
        this.clueForm.taskId = row.processinstanceid
        this.clueForm.isViewNum = 1
        this.clueForm.formId = row.formId
      },
      /**
       * 保存线索后刷新列表
       */
      handleSubmit() {
        this.reloadList()
      },
      /**
       * 查看流程图
       * @param row
       */
      handleViewFlow(row) {
        this.flowDialogVisible = !this.flowDialogVisible;
        this.loading = true;
        this.getClueNodes({
          processdefinitionid: row.processdefinitionid,
          processinstanceid: row.processinstanceid
        }).then(res => {
          this.returnShow = false;
          this.processList = res;
          this.$nextTick(function () {
            let arrDom = [],
              arr = [];
            const r = 55,
              lineWidth = 15,
              padding = 10;
            this.processList.forEach((val, index) => {
              if (index === 0 || val.result === '0') {
                arrDom.push(this.$refs.process[index].querySelector('.process-circle'))
                arr.push(this.$refs.process[index].querySelector('.process-circle').offsetLeft)
              }

              if (val.result === '1' || val.result === '0') {
                let classVal = this.$refs.process[index].querySelector('.process-circle').getAttribute('class').concat(' process-circle-pass');
                this.$refs.process[index].querySelector('.process-circle').setAttribute('class', classVal)
                if (val.result === '1') {
                  let classline = this.$refs.process[index].querySelector('.process-line').getAttribute('class').concat(' process-line-pass');
                  this.$refs.process[index].querySelector('.process-line').setAttribute('class', classline)
                }
              }
            });
            if (arrDom.length > 1) {
              this.returnShow = true;
              this.leftStyleNum = arrDom[0].offsetLeft + r - lineWidth / 2 + 'px';
              this.rightStyleNum = arrDom[1].offsetLeft + r - lineWidth / 2 + 'px';

              let left = arr.reduce((left, right) => left + right) / 2;
              this.circleStyleNum = left + 'px';
              this.leftLineStyleWidth = left + padding - r + 'px';
              this.rightLineStyleLeft = left - lineWidth + r * 2 + 'px';
            }

            this.loading = false;
          })
        })
      },
      /**
       * 删除线索
       * @param row
       */
      handleRemove(row) {
        this.currentModel = {...row}
        this.deleteReason = null
        this.removeDialogVisible = false
      },
      removeDialogCancel() {
        this.removeDialogVisible = !this.removeDialogVisible
      },
      removeDialogSave() {
        this.vm['deleteClue']({
          processinstanceid: this.currentModel.processinstanceid,
          yy: this.deleteReason
        }).then(res => {
          this.removeDialogVisible = !this.removeDialogVisible
          this.reloadList()
        })
      },
      /**
       *  选择表单
       */
      handleFormList(row) {
        this.currentModel = {...row}
        this.clueForm.formId = null
        this.formDialogVisible = false
      },
      formDialogCancel() {
        this.formDialogVisible = !this.formDialogVisible
      },
      formDialogSave() {
        this.handleAddClue()
        this.formDialogCancel()
      }
    },
    beforeDestroy() {
      off(window, 'click', this.showFilterRow)
    },
    watch: {
      query: {
        deep: true,
        handler(val) {
          this.queryData = Object.assign({}, val)
          this.$nextTick(() => {
            this.getTableCols()
            this.reloadList()
          })
        }
      }
    }
  }
</script>
